package com.example.lj.uav.view;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.view.base.BaseActivity;

import java.io.File;
import java.util.List;

import dji.common.camera.SettingsDefinitions;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.sdk.camera.Camera;
import dji.sdk.camera.PlaybackManager;
import dji.sdk.media.DownloadListener;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;

public class MediaPlayerActivity extends BaseActivity implements Handler.Callback {
    private MediaFile mediaFile;
    private MediaManager mediaManager;
    private Camera camera;
    private int position;
    private VideoView mVv;
    private Handler mHandler;
    private ProgressBar mPb;
    private TextView mTvProgress;
    private String folderUrl;
    private boolean isDownloading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        mVv = findViewById(R.id.vv_video_player);
        mPb = findViewById(R.id.pb_media_download_progress);
        mTvProgress = findViewById(R.id.tv_media_download_progress);
        initData();
    }

    private void initData() {
        mHandler = new Handler(this);
        Intent intent = getIntent();
        position = intent.getIntExtra("camera",0);
        List<Camera> cameras = MyApplication.getProductInstance().getCameras();
        if (cameras.size()>0){
            camera = cameras.get(position);
        }else{
            showToast("请连接相机");
            this.finish();
            return;
        }
        mediaFile = (MediaFile) intent.getSerializableExtra("media");
        mediaManager = camera.getMediaManager();
        camera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError==null){
                    mHandler.sendEmptyMessage(0);
                }

            }
        });
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what){
            case 0:
                folderUrl = Environment.getExternalStorageDirectory()+"UAV/MEDIA";
                final File storageFolder = new File(folderUrl);
                mediaFile.fetchFileData(storageFolder, null, new DownloadListener<String>() {
                    @Override
                    public void onStart() {
                        mPb.setVisibility(View.VISIBLE);
                        mTvProgress.setVisibility(View.VISIBLE);
                        isDownloading = true;
                    }

                    @Override
                    public void onRateUpdate(long l, long l1, long l2) {

                    }

                    @Override
                    public void onProgress(long total, long current) {
                        int progress = (int) (current/total*100);
                        mPb.setProgress(progress);
                        mTvProgress.setText(progress+"%");
                    }

                    @Override
                    public void onSuccess(String s) {
                        mPb.setVisibility(View.GONE);
                        mTvProgress.setVisibility(View.GONE);
                        playVideo();
                        isDownloading = false;
                    }

                    @Override
                    public void onFailure(DJIError djiError) {
                        mPb.setVisibility(View.GONE);
                        mTvProgress.setVisibility(View.GONE);
                    }
                });
                break;
        }
        return false;
    }

    private void playVideo() {
        String path = folderUrl+"/"+mediaFile.getFileName();
        mVv.setVideoPath(path);

        MediaController mediaController = new MediaController(this);

        mVv.setMediaController(mediaController);

        mVv.requestFocus();
        mVv.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction()==KeyEvent.ACTION_DOWN){
            if (isDownloading){
                showToast("正在下载中，请勿退出");
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaManager.stop(null);
//        mediaManager.removeFileListStateCallback(this.updateFileListStateListener);
//        mediaManager.removeMediaUpdatedVideoPlaybackStateListener(updatedVideoPlaybackStateListener);
        mediaManager.exitMediaDownloading();
//        if (scheduler!=null) {
//            scheduler.removeAllTasks();
//        }
    }
}
